<template>
	<!-- <a-row :gutter="24">
		<a-col :span="2">
			<a-form-item>
				<a-button type="primary" @click="formRef.onOpen({ debtorCardId: props.debtorCardId })">
					<template #icon>
						<plus-outlined/>
					</template>
					新增
				</a-button>
			</a-form-item>
		</a-col>
		<a-col :span="20">
			<a-form-item label="自定义展示信息：">{{ htWebCall.customerInfo }}</a-form-item>
		</a-col>
	</a-row> -->
	<a-table
		ref="tableRef"
		:size="5"
		:pageSizeOptions="['5', '10', '20']"
		:columns="columns"
		:data-source="liaisonList"
		:row-key="(record) => record.id"
		:pagination="pagination"
		@change="handleTableChange"
		:scroll="{ x: 'max-content' }"
	>
		<template #bodyCell="{ column, text, record }">
			<template v-if="column.dataIndex === 'action'">
				<a-space>
					<a-button type="link" primary size="small" :disabled="callDisabled"
							  @click="openTemplateModal(record.id)" v-if="hasPerm('sendCaseSms')">
						发送
					</a-button>
					<a-button type="link" primary size="small" :disabled="callDisabled" @click="toCall(record)">拨打
					</a-button>
					<a-button type="link" primary size="small" @click="formRef.onOpen(record)">修改</a-button>
					<a-button type="link" primary size="small" v-if="record.phoneSource === '3'"
							  @click="deleteLiaison(record.id)"
					>删除
					</a-button>
					<a-button type="link" primary size="small" @click="complaintFormRef.onOpen(props.complaintInfo)">拉黑</a-button>
				</a-space>
			</template>
			<template v-if="column.dataIndex === 'liaisonPhone'">
				<a-space>
					{{ text }}
				</a-space>
				<a-tooltip title="明文" v-if="!isSentive()">
					<a-button type="link" @click="showPlainPhone(record)" class="icon-button">
						<EyeOutlined/>
					</a-button>
				</a-tooltip>
			</template>
		</template>
	</a-table>
	<Form ref="formRef" @successful="pageList(pagination.current)"/>
	<!-- 拉黑投诉用户表单 -->
	<ComplaintForm ref="complaintFormRef" @successful="pageList(pagination.current)"/>
	<a-modal v-model:open="smsTemplateModal" @ok="sendSms">
		<a-form class="mt-10" ref="smsFormRef" :model="smsFormData">
			<a-form-item label="短信模版">
				<a-select v-model:value="smsFormData.templateCode" @change="changeTemplate"
						  placeholder="请选择短信模版">
					<a-select-option v-for="option in templateList" :key="option.templateCode"
									 :value="option.templateCode"
									 :label="option.templateName">
						{{ option.templateName }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="变量" v-for="(item, index) in items" :key="index">
				<a-input
					v-model:value="item.value"
					placeholder="请输入内容"
				/>
			</a-form-item>
			<a-form-item label="短信内容">
				<a-textarea
					v-model:value="smsFormData.smsContent"
					:auto-size="{ minRows: 8, maxRows: 15 }"
					:disabled="true"
				/>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup name="liaison">
import liaisonApi from '@/api/tjzy/liaison/liaisonApi'
import Form from '@/views/tjzy/case/detail/liaison/form.vue'
import ComplaintForm from '@/views/tjzy/complaint/form.vue'
import {Modal} from 'ant-design-vue'
import {createVNode} from 'vue'
import {ExclamationCircleOutlined} from '@ant-design/icons-vue'
import smsTemplateApi from "@/api/tjzy/sms/smsTemplateApi";
import workApi from "@/api/tjzy/work/workApi";
import { isSentive } from '@/utils/permission/index'

const props = defineProps({
	debtorCardId: String,
	caseId: String,
	projectCode:String,
	complaintInfo: Object,
})
// console.log('complaintInfo',props.complaintInfo);
const smsTemplateModal = ref(false)
const templateList = ref([])
const smsFormData = ref({})
const smsFormRef = ref()
const emit = defineEmits({ callEvent: Object,liaisonSelfEvent:Object})
const pagination = ref({
	current: 1, // 当前页码
	pageSize: 10, // 每页条数
	total: 0, // 数据总量
	showSizeChanger: true, // 是否可以改变每页数量
	pageSizeOptions: ['5', '10', '20'],
	showTotal: (total, range) => {
		return `${range[0]}-${range[1]} 共 ${total} 条 `
	}
})
const items = ref([])
const searchFormState = ref({
	current: 1,
	size: 5,
	debtorCardId: props.debtorCardId
})
const tableRef = ref()
const formRef = ref()
const complaintFormRef = ref()
// console.log('子组件里获取的孙',formRef);

emit('formEvent', formRef)

const liaisonList = ref([])
const callDisabled = ref(false)
const columns = [
	{
		title: '姓名',
		dataIndex: 'liaisonName'
	},
	{
		title: '关系',
		dataIndex: 'relationship'
	},
	{
		title: '电话',
		dataIndex: 'liaisonPhone'
	},
	{
		title: '是否可用',
		dataIndex: 'phoneStatusName'
	},
	{
		title: '所属项目',
		dataIndex: 'productName'
	},
	{
		title: '来源',
		dataIndex: 'phoneSourceName'
	},
	{
		title: '今日拨打次数',
		dataIndex: 'todayCallCount'
	},
	{
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		fixed: 'right'
	}
]



// //添加联系人
// const addContact = () => {
//     formRef.onOpen({ debtorCardId: props.debtorCardId })
// }
const handleTableChange = (pagination, filters, sorter) => {
	// console.log(pagination)
	if (!(searchFormState.value.current === pagination.current && searchFormState.value.size === pagination.pageSize)) {
		searchFormState.value.current = pagination.current
		searchFormState.value.size = pagination.pageSize
		pageList(searchFormState.value.current)
	}
}

const pageList = (current) => {
	
	searchFormState.value.current = current
	liaisonApi.liaisonPage(searchFormState.value).then((res) => {
		liaisonList.value = res.records
		// console.log('liaisonList',liaisonList.value)
		pagination.value.total = res.total
		pagination.value.current = res.current
		pagination.value.pageSize = res.size
		const liaison = liaisonList.value.find(item => item.relationship === '本人');
		emit('liaisonSelfEvent', liaison)
	})
}

const openTemplateModal = (id) => {
	smsFormData.value.liaisonId = id
	smsTemplateModal.value = true
}

const parseItems = (text) => {
	// 假设变量名是独立的单词，且以 "item" 开头
	const regex = /\bitem\d+\b/g;
	const matches = text.match(regex);
	if (matches) {
		items.value = matches.map(match => ({
			key: match, // 直接使用匹配到的变量名
			value: ''
		}));
	} else {
		items.value = [];
	}
};

const changeTemplate = (val) => {
	const item = templateList.value.find(item => item.templateCode === val);
	smsFormData.value.smsContent = item ? item.templateContent : null;
	smsFormData.value.supplierCode = item ? item.supplierOrder.split(",")[0] : null;
	parseItems(smsFormData.value.smsContent);
};

const sendSms = () => {
	// console.log(items.value)
	const allFilled = items.value.every(item => item.value.trim() !== '');
	if (!allFilled) {
		Modal.error({
			title: '提示',
			content: '所有变量均为必填项，请填写完整后再发送！',
			icon: createVNode(ExclamationCircleOutlined),
		});
		return;
	}
	let smsContent = smsFormData.value.smsContent;
	items.value.forEach(item => {
		const regex = new RegExp(`\\b${item.key}\\b`, 'g'); // 构造正则表达式，匹配变量名
		smsContent = smsContent.replace(regex, item.value); // 替换变量为实际值
	});
	// 将替换后的短信内容保存到 formData 中
	smsFormData.value.smsContent = smsContent;
	smsFormData.value.caseId = props.caseId
	workApi.addWordBySms(smsFormData.value).then((res) => {
		smsTemplateModal.value = false
		emit('smsEvent', null)
	})
}

const showPlainPhone = (record) => {
	liaisonApi.getLiaisonPhoneById(record.id, false).then((res) => {
		// console.log(res)
		record.liaisonPhone = res.liaisonPhone
	})
}

const toCall = (record) => {
	liaisonApi.getLiaisonPhoneById(record.id, true).then((res) => {
		if (res != null) {
			if (res.msg != null) {
				Modal.confirm({
					title: '提示',
					content: res.msg,
					icon: createVNode(ExclamationCircleOutlined),
					maskClosable: false,
					okText: '确定',
					cancelText: '取消',
					onOk() {
						addWordAndCall(res.liaisonPhone, record)
					},
					onCancel() {
					}
				})
			} else {
				addWordAndCall(res.liaisonPhone, record)
			}
		}
	})
}
const addWordAndCall = (liaisonPhone, record) => {
	//增加电话拨打次数
	liaisonApi.addPhoneTodayCallCount(liaisonPhone).then((res) => {
		pageList(searchFormState.value.current)
		callDisabled.value = true
		setTimeout(() => {
			callDisabled.value = false
		}, 3000)
	})
	const params = {
		callRecipient: record.relationship,
		relationship: record.relationship,
		workType: 1,
		debtorCardId: props.debtorCardId,
		liaisonName: record.liaisonName,
		liaisonPhone: liaisonPhone,
		projectCode:props.projectCode
	}
	emit('callEvent', params)
}
const deleteLiaison = (id) => {
	Modal.confirm({
		title: '提示',
		content: '确定删除此手机号？',
		icon: createVNode(ExclamationCircleOutlined),
		maskClosable: false,
		okText: '确定',
		cancelText: '取消',
		onOk() {
			liaisonApi.deleteById(id).then((res) => {
				pageList(pagination.value.current)
			})
		},
		onCancel() {
		}
	})
}
onMounted(() => {
	pageList(1)
	smsTemplateApi.list().then(res => {
		templateList.value = res;
	})
})
defineExpose({
	formRef
})
</script>
